<?php

namespace app\index\controller;
use think\Db;


class Reg extends \think\Controller
{
    private function SendActiveMail($username,$qq,$name,$ActiveCode)   //发送激活邮件
    {

        $tomail=$qq.'@qq.com';
        $body= 'http://'.$_SERVER['HTTP_HOST'].'/Index/Reg/Verify.html?qq='.$qq.'&ActiveCode='.$ActiveCode;
        $body="亲爱的".$name."同学，你已经完成了湖工志愿平台的注册，您的账号为<br>\n".$username."<br>\n，接下来需要您来激活以确认你是真人，请点击以下链接激活：\n<br><a href='".$body."'>".$body."</a>";
        send_mail($tomail,$name,'注册成功！请激活',$body);
    }


    public function register()  //注册页面显示
    {
        return $this->fetch('index/register');
    }
    public function RegJson()   //注册接口
    {

        $qq=Db::name('users')->where('qq',input('post.qq'))->find();
        $username=Db::name('users')->where('username',input('post.username'))->find();
        if(!empty($qq)&&$qq['active']==0)
        {

            $ActiveCode=GetRandStr(20);
            Db::name('users')->where('qq',input('post.qq'))->update(['ActiveCode'=>$ActiveCode,'phone'=>input('post.phone'),'password'=>md5(input('post.password'))]);
            $this->SendActiveMail($qq['username'],$qq['qq'],$qq['name'],$ActiveCode);
            //TODO 发送邮件
            return json(['msg'=>'用户未激活，已重新发送邮件，请激活','result'=>'error']);
        }
        if(!empty($username)||!empty($qq))
        {
            return json(['msg'=>'用户名存在','result'=>'error']);
        }
        $ActiveCode=GetRandStr(20);
        $input=input('post.');
        $input['ActiveCode']=$ActiveCode;
        $input['password']=md5($input['password']);
        //TODO 发送邮件
        $this->SendActiveMail($input['username'],$input['qq'],$input['name'],$input['ActiveCode']);

        $CollegeData=Db::name('college')->where("college_name",$input["college"])->find();
        if(empty($CollegeData))
        {
            Db::name('college')->insert(["college_name"=>$input["college"]]);
        }
        $MajorData=Db::name('major')->where("major_name",$input["major"])->find();
        if(empty($MajorData))
        {
            Db::name('major')->insert(["major_name"=>$input["major"]]);
        }

        $insert=Db::name('users')->insert($input);
        if($insert){
            return json(['result'=>'success']);
        }else{
            return json(['msg'=>'程序错误，请联系计科青协处理','result'=>'error']);
        }

    }

    public function Verify()  //注册验证
    {
        $user=Db::name('users')->where(['qq'=>input('get.qq'),'ActiveCode'=>input('get.ActiveCode')]);
        if (!empty($user->find()))
        {
            $result=Db::name('users')->where(['qq'=>input('get.qq'),'ActiveCode'=>input('get.ActiveCode')])->update(['active'=>1]);
            if($result){
                $this->success('验证成功，正在跳转到登录页面','../../index');
            }else{
                $this->error('验证失败');
            }
        }else{
            $this->error('验证失败');
        }
    }
}
